package edu.ccut.saturn.basecomponent.database.facade;

import java.sql.Connection;
import java.util.Map;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.SaturnSQLHandler;
import edu.ccut.saturn.basecomponent.database.impl.SaturnSQL;
import edu.ccut.saturn.basecomponent.database.util.SaturnDataUtil;
import edu.ccut.saturn.component.IDataInfo;
import edu.ccut.saturn.component.SaturnData;

public class UpdateBySaturnSQL {
	public int execute(String fullKey, String sqlKey, Map<String, Object> paramMap,
			Connection conn) throws Exception {
		
		if (fullKey != null){
			SaturnData saturnData = SaturnDataUtil.getSaturnData(fullKey);
			
			IDataInfo dataInfo = saturnData.getSaturnDataInfo();
			
			String dbType = dataInfo.getDBType();
			
			if (sqlKey != null && paramMap.size() >0 && conn != null){
				String sql = dataInfo.getSqlById(sqlKey, paramMap);
			
				SaturnSQL saturnSQL = new SaturnSQL();
				
				saturnSQL.setDBtype(dbType);
				saturnSQL.setOperationType(getBuilderType(saturnData));
				saturnSQL.setSaturnDataFullKey(fullKey);
				saturnSQL.setSql(sql);
				int count = SaturnSQLHandler.executeUpdate(saturnSQL,conn);
				return count;
			}
		}
		return -1;
	}

	private String getBuilderType(SaturnData saturnData) {
		// 如果有大数据
		if (SaturnDataUtil.hasLOB(saturnData)) {
			return ISaturnSQL.UPDATE_LOB_OPERATION;
		} else {
			return ISaturnSQL.UPDATE_OPERATION;
		}
	}
}
